// pages/mine/regist/testphonenumber/testphonenumber.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    requrl: 'https://testapp.1sju.com/yishuju-app/',
    phoneNumber: '',
    phoneNum: '',
    countDownTime: 60,
    focus: true,
    codeList: [], // 验证码数组，用来遍历动态生成input
    focusInputList: null, // input光标index对应数组
    tempCode: '', // 输入时临时验证码
    askCoce: '',
    identifyingCode: '123456' // 请求得到的验证码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    let self = this
    let phoneNum = self.strDeal(options.phoneNum || '13113864577')
    let codeArr = self.cutidentCode()
    self.setData({
      phoneNumber: phoneNum,
      phoneNum: options.phoneNum,
      codeList: codeArr
    })
    self.setFocusArr(0, 6)
    self.getCountDownTime()
    // 页面一加载，就请求验证码，然后将请求得到的验证码,赋值给 identifyingCode
    self.getIndentifyCode()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  /**
   * 输入验证码需要执行的逻辑
   */
  codeInput: function (value) {
    let self = this
    console.log('value``````value', value)
    if (value.detail.value !== '') {
      self.codeSplitJoint(value.detail.value, value.currentTarget.dataset.index)
      self.setFocusArr(value.currentTarget.dataset.index, 6, value.detail.value)
    }
    if (self.data.tempCode.length === 6) {
      if (+self.data.countDownTime > 0) { // 判断验证码是否过期
        self.ackCode()
      } else {
        // wx.showToast({
        //   title: '验证码过期',
        //   image: '../../../../resource/icon/notice@2x.png',
        //   duration: 2000
        // })
      }
    }
    // if (value.detail.value === ''){
    //   self.codeSplitJoint(value.detail.value, value.currentTarget.dataset.index)
    //   self.setFocusArr(self.data.tempCode.length-1)
    // }
  },
  topCodeInput:function(e){
    this.data.tempCode = e.detail.value
    if (this.data.tempCode.length === 6) {
      if (+this.data.countDownTime > 0) { // 判断验证码是否过期
        this.ackCode()
      } else {
        // wx.showToast({
        //   title: '验证码过期',
        //   image: '../../../../resource/icon/notice@2x.png',
        //   duration: 2000
        // })
      }
    }
  },
  /**
   * 验证码拼接
   */
  codeSplitJoint: function (value, index) {
    if (value === ''){
      // var newstr = this.data.tempCode
      // this.data.tempCode = newstr.substr(newstr, newstr.length - 1)
      // console.log('codeSplitJoint`````tempCode', this.data.tempCode)
      return
    } 
    let self = this
    if (index === self.data.tempCode.length) {
      this.data.tempCode = self.data.tempCode + value
      // self.setData({
      //   tempCode: self.data.tempCode + value
      // })
    }
    if (index < self.data.tempCode.length) {
      let str = self.data.tempCode
      // 删除原位置的验证码数字，再用新的替换
      let arr = str.split('')
      arr.splice(index, 1, value)
      let tempStr = ''
      for (let i = 0; i < str.length; i++) {
        tempStr += arr[i]
      }
      this.data.tempCode = tempStr
      // self.setData({
      //   tempCode: tempStr
      // })
    }
    console.log('codeSplitJoint`````tempCode', self.data.tempCode)
  },
  /**
   * 重新发送请求验证码
   */
  resend: function () {
    let self = this
    let codeArr = self.cutidentCode()
    self.setData({
      codeList: codeArr,
      tempCode: ''
    })
    self.setFocusArr(0, 6)
    self.getCountDownTime()
    self.getIndentifyCode()
  },
  /**
   * 请求验证码
   */
  getIndentifyCode: function () {
    let self = this
    self.setData({
      countDownTime: 60,
      tempCode: ''
    })
    let params = {
      'account': self.data.phoneNum,
      'sms_code': 'No',
      'send': 'send'
    }
    wx.request({
      url: wx.envConfig.host + '/user/requestVerifyCode?params=' + JSON.stringify(params),
      method: 'POST',
      success: function (res) {
        console.log('res', res)
        if (res && res.datas) {
          self.setData({
            identifyingCode: res.datas
          })
        }
      },
      fail: function (err) {
        // 请求错误提示
        console.log('err', err)
      }
    })
  },
  /**
   * 校验验证码
   */
  ackCode: function () {
    let self = this
    let params = {
      'account': self.data.phoneNum,
      'sms_code': self.data.tempCode
    }
    wx.request({
      url: wx.envConfig.host + '/user/ackCode?params=' + JSON.stringify(params),
      method: 'POST',
      success: function(res) {
        if (res && res.data) {
          self.setData({
            askCoce: res.data.datas
          })
          console.log('askCoce', self.data.askCoce)
          if (res.data.datas === 'succ') {
            wx.redirectTo({
              url: './identifyingcode/identifyingcode?phoneNum=' + self.data.phoneNum + '&psw=' + self.data.psw + '&identifyingCode=' + self.data.tempCode,
              success: function(res) {},
              fail: function(res) {},
              complete: function(res) {},
            })
          }
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  /**
   * 字符串星号处理
   */
  strDeal: function (str) {
    if (!(str + '')) {
      return
    }
    str = str + ''
    let strHead = str.substring(0, 3)
    let strTail = str.substring(7)
    let strResult = strHead + '****' + strTail
    return strResult
  },
  /**
   * 倒计时
   */
  getCountDownTime: function () {
    let self = this
    let timer = setInterval(function () {
      self.setData({
        countDownTime: +self.data.countDownTime - 1
      })
      if (((self.data.countDownTime * 1) === 0) || (self.data.tempCode.length === 6 && self.data.askCoce !== '' && self.data.askCoce !== 'succ')) {
        clearInterval(timer)
      }
    }, 1000)

    if (!timer) {
      return
    }
  },
  /**
   * 分割验证码
   */
  cutidentCode: function (str) {
    // return ['', '', '', '', '', '']
    if (!str) return ['', '', '', '', '', '']
    str += ''
    let strArr = str.split('')
    return strArr
  },
  /**
   * 设置fouus布尔数组
   */
  setFocusArr: function (index, length, value) {
    if (!length) length = 6
    if (!value) value = ''
    let self = this
    let arr = []
    // if (self.data.countDownTime <= 0 || (self.data.tempCode.length >= 6 && self.data.identifyingCode !== self.data.tempCode)) {
    //   for (let i = 0; i < length; i++) {
    //     arr[i] = false
    //   }
    //   self.setData({
    //     focusInputList: arr
    //   })
    //   return
    // }
    if (value === '') {
      for (let i = 0; i < length; i++) {
        if (i <= index) {
          arr[i] = true
        } else {
          arr[i] = false
        }
      }
    }
    if (value !== '') {
      console.log('value````````setFocus', arr)
      for (let i = 0; i < length; i++) {
        if (index === (length - 1)) {
          arr[i] = true
        } else if (i <= index + 1) {
          arr[i] = true
        } else {
          arr[i] = false
        }
      }
    }
    self.setData({
      focusInputList: arr
    })
  }
})